CC=gcc
TARGET=../bin/kernel.elf
BIN=../bin/Enjoy.bin
LIBS=-lx64plat  -lcpuid -lmem -lintr -lprint -ldisk -lpit -lkeybrd
LDFLAGS=-L./obj -b elf64-x86-64  -e _dragon -z muldefs -z noexecstack 
CFLAGS=-Wall  -Wextra -Werror -I./include -I./include/driver -mcmodel=large -fno-builtin -m64  -nostdlib -nolibc -nostdinc -fno-stack-protector -nostartfiles -nodefaultlibs -ffreestanding

exclude_dirs:=include obj bin
ifeq ($(DEBUG),ON)
CFLAGS+=-g3
else
LDFLAGS+= -O2
endif
#commom must be compiled before any other modules
start_dirs:=./mbr ./boot

subdir=$(shell find . -maxdepth 1 -type d)
dirs+=$(filter-out $(start_dirs), $(subdir))
dirs:=$(basename $(patsubst ./%,%,$(dirs)))
dirs:=$(filter-out $(exclude_dirs),$(dirs))
start_dirs+=$(dirs)

.PHONY: $(start_dirs) clean

all: $(TARGET)

$(TARGET): $(start_dirs) main.o
	ld  -o $@ $(LDFLAGS)  ./obj/head.o main.o $(LIBS) -T my.lds
	objcopy -I elf64-x86-64 -S -R ".eh_frame" -R ".comment" -O binary $(TARGET) $(BIN)

main.o: main.c
	$(CC) $(CFLAGS) -c $< -o $@

$(start_dirs):
	@for dir in $(start_dirs); do \
		$(MAKE) -C $$dir || exit $$?; \
	done

clean:
	rm -f $(TARGET) $(BIN) main.o
	@for dir in $(start_dirs); do \
		$(MAKE) -C $$dir clean || exit $$?; \
	done
